package com.disruptor.event;

import com.disruptor.bean.ProConProperties;
import com.disruptor.disruptor.ProConMain;
import com.disruptor.util.HelpMe;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;

import javax.sql.DataSource;

/**
 * Created by mengdexuan on 2017/5/18 17:59.
 */
public class DealWithStartedEvent implements ApplicationListener<ContextRefreshedEvent> {

	private static Logger log = LoggerFactory.getLogger(DealWithStartedEvent.class);
	private ActiveRecordPlugin arp = null;


	@Override
	public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
		ApplicationContext appContext = contextRefreshedEvent.getApplicationContext();

		DataSource ds = appContext.getBean(DataSource.class);
		arp = new ActiveRecordPlugin(HelpMe.uuid(),ds);
		arp.start();

		ProConProperties proConProperties = appContext.getBean(ProConProperties.class);

		log.info("disruptor 配置信息 --> "+proConProperties);

		ProConMain.start(proConProperties.getBufferSize(),proConProperties.getConsumerThreadNum());

		log.info("项目启动完毕！");

		hook();
	}

	public void hook(){
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run() {
				log.info("jvm 关闭，触发钩子函数……");
				ProConMain.stop();
				if (arp!=null){
					arp.stop();
					arp = null;
				}
			}
		});
	}
}
